import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import toolRouters from './modules/tool'
import pageRouters from './modules/page'
import userRouters from './modules/user'
import gmRouters from './modules/gm'
import adminRouters from './modules/admin'
import { bus } from '@/utils/bus'

Vue.use(VueRouter)

const routes = [
  ...adminRouters,
  ...gmRouters,
  ...userRouters,
  ...toolRouters,
  ...pageRouters
]

const router = new VueRouter({
  mode: 'history',
  base: import.meta.env.BASE_URL,
  routes,
  scrollBehavior() {
    return { x: 0, y: 0 }
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch((err) => err)
}

// 导航守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title + '-云深不知处'
  // const token = store.state.user.satoken
  const token = store.getters.satoken
  // 没登录却访问user下的路由
  if (!token && to.meta.auth) {
    return next('/login?returnUrl=' + encodeURIComponent(to.fullPath))
  }
  // 其他情况放行
  // localStorage.setItem('activeUrl', to.path)
  bus.$emit('toPage', to.path)
  next()
})

export default router
